from django.shortcuts import render
from rest_framework.viewsets import ReadOnlyModelViewSet
from rest_framework_extensions.cache.mixins import CacheResponseMixin

# Create your views here.
from areas.models import Area
from .serializers import AreaSerializer, SubAreaSerializer


class AreasViewSet(CacheResponseMixin, ReadOnlyModelViewSet):
    """
    省市区三级联动: 视图集
    CacheResponseMixin 这个mixin是用drf-extensions拓展实现查询方法数据(不经常改变的数据)缓存到redis中
    """
    pagination_class = None  # 信息不分页

    def get_queryset(self):
        """根据不同的行为, 使用不同的查询集"""
        if self.action == 'list':
            return Area.objects.filter(parent=None)
        else:
            return Area.objects.all()

    def get_serializer_class(self):
        """根据不同的行为: 使用不同的序列化器"""
        if self.action == 'list':
            return AreaSerializer
        else:
            return SubAreaSerializer
